package com.irate.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.http.Header;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;
import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.User;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;

public class CreateAccountActivity extends Activity {

	protected SimpleFacebook fb;
	protected TextView sign_up_fb;
	protected ImageView ic_back;
	protected ImageView ic_forward;

	protected EditText txt_email;
	protected EditText txt_password;
	protected EditText txt_firstName;
	protected EditText txt_lastname;
	protected RadioGroup txt_sex;
	protected Spinner txt_age_group;
	protected Spinner txt_region;

	protected ImageView avatar;
	protected UserDAO userDAO;
	protected String avatar_pic;

	protected ProgressDialog dialog;

	private static final String TAG = "FileChooserExampleActivity";

	private static final int REQUEST_CODE = 6384; // onActivityResult request
													// code

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_account);

		init();
		execute();
	}

	private void init() {
		fb = SimpleFacebook.getInstance(this);

		sign_up_fb = (TextView) findViewById(R.id.create_account_up_fb_button);
		ic_back = (ImageView) findViewById(R.id.create_account_back_button);
		ic_forward = (ImageView) findViewById(R.id.create_account_forward_button);

		txt_email = (EditText) findViewById(R.id.email);
		txt_password = (EditText) findViewById(R.id.password);
		txt_firstName = (EditText) findViewById(R.id.create_account_first_name);
		txt_lastname = (EditText) findViewById(R.id.create_account_last_name);
		txt_sex = (RadioGroup) findViewById(R.id.create_account_group_sex);
		txt_age_group = (Spinner) findViewById(R.id.create_account_age_range_spinner);
		txt_region = (Spinner) findViewById(R.id.create_account_region_spinner);

		avatar = (ImageView) findViewById(R.id.avatar);

		userDAO = new UserDAO();
	}

	// private void showChooser() {
	// // Use the GET_CONTENT intent from the utility class
	// Intent target = FileUtils.createGetContentIntent();
	// // Create the chooser Intent
	// Intent intent = Intent.createChooser(target,
	// getString(R.string.chooser_title));
	// try {
	// startActivityForResult(intent, REQUEST_CODE);
	// } catch (ActivityNotFoundException e) {
	// // The reason for the existence of aFileChooser
	// }
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		fb.onActivityResult(this, requestCode, resultCode, data);

		switch (requestCode) {
		case REQUEST_CODE:
			// If the file selection was successful
			if (resultCode == RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					Log.i(TAG, "Uri = " + uri.toString());
					try {
						// Get the file path from the URI
						final String path = FileUtils.getPath(this, uri);

						if (path != null) {
							avatar_pic = path;
						} else {
							avatar_pic = getBitmap("avatar", uri);
						}

						Bitmap bm = BitmapFactory.decodeFile(avatar_pic);
						avatar.setImageBitmap(bm);

					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private String getBitmap(String tag, Uri url) {
		File cacheDir;
		// if the device has an SD card
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					".OCFL311");
		} else {
			// it does not have an SD card
			cacheDir = this.getCacheDir();
		}
		if (!cacheDir.exists())
			cacheDir.mkdirs();

		File f = new File(cacheDir, tag);
		try {
			if (f.exists()) {
				f.delete();
				f.createNewFile();
			} else {
				f.createNewFile();
			}

		} catch (Exception e) {

		}
		try {
			InputStream is = null;
			if (url.toString().startsWith(
					"content://com.google.android.gallery3d")) {
				is = getContentResolver().openInputStream(url);
			} else {
				is = new URL(url.toString()).openStream();
			}
			OutputStream os = new FileOutputStream(f);

			byte[] buffer = new byte[1024];
			int len;
			while ((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}

			os.close();
			return f.getAbsolutePath();
		} catch (Exception ex) {
			// something went wrong
			ex.printStackTrace();
			return null;
		}
	}

	private void execute() {
		sign_up_fb.setOnClickListener(signUpFaceBook);

		avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// showChooser();
			}
		});

		ic_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		ic_forward.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				User userInfor = new User();
				userInfor.setEmail(txt_email.getText().toString());
				userInfor.setFirst_name(txt_firstName.getText().toString());
				userInfor.setLast_name(txt_lastname.getText().toString());
				userInfor.setRegion(txt_region.getSelectedItem().toString());
				userInfor
						.setSex(txt_sex.getCheckedRadioButtonId() == R.id.female ? getResources()
								.getString(R.string.female) : getResources()
								.getString(R.string.male));
				userInfor.setAge(txt_age_group.getSelectedItem().toString());

				dialog = ProgressDialog.show(CreateAccountActivity.this,
						getResources().getString(R.string.res), getResources()
								.getString(R.string.loading), true);
				userDAO.register(userInfor, txt_password.getText().toString(),
						handler, CreateAccountActivity.this, dialog);

			}
		});
	}

	OnClickListener signUpFaceBook = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (fb.isLogin()) {
				fb.logout(new OnLogoutListener() {

					@Override
					public void onFail(String reason) {
					}

					@Override
					public void onException(Throwable throwable) {
					}

					@Override
					public void onThinking() {
					}

					@Override
					public void onLogout() {
						login();
					}

				});
			} else {
				login();
			}

		}
	};

	private void login() {
		fb.login(new OnLoginListener() {

			@Override
			public void onFail(String reason) {
			}

			@Override
			public void onException(Throwable throwable) {
			}

			@Override
			public void onThinking() {
			}

			@Override
			public void onNotAcceptingPermissions() {
			}

			@Override
			public void onLogin() {
				startActivity(new Intent(CreateAccountActivity.this,
						MainActivity.class));
				finish();
			}
		});
	}

	AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			Toast.makeText(CreateAccountActivity.this,
					getResources().getString(R.string.res_success),
					Toast.LENGTH_LONG).show();
			// Handler handler = new Handler();

			// handler.postDelayed(new Runnable() {
			//
			// @Override
			// public void run() {
			// if (avatar_pic != null && avatar_pic != "") {
			// userDAO.upLoadPhoto(new File(avatar_pic), handlerUpload);
			//
			// } else {
			startActivity(new Intent(CreateAccountActivity.this,
					LoginActivity.class));
			finish();
			//
			// }
			// }, 1000);
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");


			Toast.makeText(CreateAccountActivity.this,
					getResources().getString(R.string.res_fail),
					Toast.LENGTH_LONG).show();
		}
	};

	// AsyncHttpResponseHandler handlerUpload = new AsyncHttpResponseHandler() {
	// @Override
	// public void onSuccess(String response) {
	// System.out.println("Success register");
	// startActivity(new Intent(CreateAccountActivity.this,
	// LoginActivity.class));
	// finish();
	// }
	//
	// @Override
	// public void onStart() {
	// System.out.println("Start");
	// }
	//
	// @Override
	// public void onFinish() {
	// if (dialog != null)
	// dialog.dismiss();
	// }
	//
	// @Override
	// public void onFailure(Throwable e, String response) {
	// System.out.println("Fail Register");
	// try {
	// JSONObject obj = new JSONObject(response);
	//
	// Toast.makeText(CreateAccountActivity.this,
	// obj.getString("message").toString(), Toast.LENGTH_SHORT)
	// .show();
	//
	// } catch (Exception ex) {
	//
	// }
	// }
	// };

	public void onBackPressed() {
		super.onBackPressed();
		startActivityForResult(new Intent(this, WelcomeActivity.class), 1);
	};
}
